import glob
import pathlib
import xml.etree.ElementTree as ET
import pickle
import shutil
import os
from os import listdir, getcwd
from os.path import join

classes = ["head"]
result_folder = "result"
FOLDER = 'D:\BaiduNetdiskDownload\SCUT_HEAD_Part_B\SCUT_HEAD_Part_B'
origin_images = f'{FOLDER}/JPEGImages'
origin_labels = f'{FOLDER}/Annotations'

origin_dataset_folder = f'{FOLDER}/data_sets'
train_folder = f'{FOLDER}/{result_folder}/train'
train_images_folder = f'{FOLDER}/{result_folder}/train/images'
train_labels_folder = f'{FOLDER}/{result_folder}/train/labels'

valid_folder = f'{FOLDER}/{result_folder}/valid'
valid_images_folder = f'{FOLDER}/{result_folder}/valid/images'
valid_labels_folder = f'{FOLDER}/{result_folder}/valid/labels'
result_folder = f'{FOLDER}/{result_folder}'


def convert(size, box):
    dw = 1. / size[0]
    dh = 1. / size[1]
    x = (box[0] + box[1]) / 2.0
    y = (box[2] + box[3]) / 2.0
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    return (x, y, w, h)


def read_data_from_dataset(f):
    with open(f) as file:
        c = file.readlines()
        return  c


def create_folder_if_not_exit(folder):
    if os.path.exists(folder):
        return
    p = pathlib.Path(folder).parent
    if not  os.path.exists(p):
        create_folder_if_not_exit(p)
    os.mkdir(folder)


def convert_annotation(fname,orgin_image_folder,origin_label_folder,target_image_folder,target_label_folder):
    print(f'{origin_label_folder}/{fname}.xml')
    in_file = open(f'{origin_label_folder}/{fname}.xml')
    out_file = open(f'{target_label_folder}/{fname}.txt' , 'w')

    tree = ET.parse(in_file)
    root = tree.getroot()
    size = root.find('size')
    w = int(size.find('width').text)
    h = int(size.find('height').text)
    # print("w,h :",w,' ',h,'\n')
    for obj in root.iter('object'):
        difficult = obj.find('difficult').text
        # 原始代码
        # cls = obj.find('name').text
        # if cls not in classes or int(difficult) == 1:

        # 自己代码
        if int(difficult) == 1 or w < 1:
            continue
        # cls_id = classes.index(cls)
        cls = 'head'
        cls_id = classes.index(cls)

        xmlbox = obj.find('bndbox')
        b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
             float(xmlbox.find('ymax').text))
        # print(float(xmlbox.find('xmin').text))
        bb = convert((w, h), b)
        out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')

    #拷贝图片到指定目录
    s = f'{orgin_image_folder}/{fname}.jpg'
    t = f'{target_image_folder}/{fname}.jpg'
    shutil.copyfile(s,t)


datasets = glob.glob(f'{origin_dataset_folder}/*.txt')
for d in datasets:
    dfolder_name = pathlib.Path(d).stem
    create_folder_if_not_exit(f'{result_folder}/{dfolder_name}')
    create_folder_if_not_exit(f'{result_folder}/{dfolder_name}/labels')
    create_folder_if_not_exit(f'{result_folder}/{dfolder_name}/images')

    img_folder = f'{result_folder}/{dfolder_name}/images'
    lab_folder = f'{result_folder}/{dfolder_name}/labels'
    content = read_data_from_dataset(d)
    for c in content:
        print(c)
        convert_annotation(c.rstrip(),origin_images,origin_labels,img_folder,lab_folder)

